package com.polaris.live.adapter.luckybag

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.polaris.live.R
import com.polaris.live.common.adapter.BaseAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.databinding.AdapterLuckyBagChatItemBinding
import com.polaris.live.databinding.AdapterLuckyBagItemBagBinding
import com.polaris.live.databinding.AdapterLuckyBagItemPromptBinding
import com.polaris.live.databinding.LayoutMessageAdapterHeadBinding
import com.polaris.live.im.utils.SessionUtils
import com.polaris.live.resp.back_resp.luckybag.LuckyBagMessageResp
import com.polaris.live.translation.R.string
import com.polaris.live.utils.DecorationUtils
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.refresh.BaseBindingViewHolder

/**
 * LuckyBagMessageAdapter
 *
 * @author Created by lucas on 2024/6/11 02:14
 * @since 1.0.0
 */
class LuckyBagMessageAdapter : BaseAdapter<LuckyBagMessageResp, BaseViewHolder>(0) {

    init {
        addChildClickViewIds(R.id.cl_left, R.id.cl_right)
    }

    override fun getDefItemViewType(position: Int): Int {
        return convertItemType(data[position])
    }

    override fun onCreateDefViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): BaseBindingViewHolder<*, *> {
        val layoutInflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            ITEM_BAG -> LuckyBagItemHolder(
                AdapterLuckyBagItemBagBinding.inflate(layoutInflater, parent, false)
            )

            ITEM_PROMPT -> LuckyBagPromptItemHolder(
                AdapterLuckyBagItemPromptBinding.inflate(layoutInflater, parent, false)
            )

            ITEM_CHAT -> LuckyBagChatItemHolder(
                AdapterLuckyBagChatItemBinding.inflate(layoutInflater, parent, false)
            )

            else -> throw IllegalArgumentException("Invalid view type: $viewType")
        }
    }

    override fun convert(holder: BaseViewHolder, item: LuckyBagMessageResp) {
        when (holder) {
            is LuckyBagItemHolder -> holder.bind(item)
            is LuckyBagPromptItemHolder -> holder.bind(item)
            is LuckyBagChatItemHolder -> holder.bind(item)
        }
    }

    private class LuckyBagItemHolder(binding: AdapterLuckyBagItemBagBinding) :
        BaseBindingViewHolder<AdapterLuckyBagItemBagBinding, LuckyBagMessageResp>(binding) {

        override fun bind(item: LuckyBagMessageResp) {
            if (item.userId == UserManager.getUser().userId) {
                setTextRight(item)
            } else {
                setTextLeft(item)
            }
        }

        private fun setTextLeft(item: LuckyBagMessageResp) {
            mBinding.apply {
                clLeft.visibility = View.VISIBLE
                clRight.visibility = View.GONE

                tvLeftTime.text =
                    SessionUtils.periodMessageTime(item.createTime)?.convertArabicDigitsToNormal()

                item.getBagMessage()?.let {
                    layoutLeftAvatar.avAvatar.setImageUrl(it.userBasic.avatar)
                    layoutLeftAvatar.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(it.userBasic.avatarFrame))

                    tvLeftNickname.text = it.userBasic.nickname
                    tvLeftCoin.text = it.coins.toString()

                    if (it.status == CommonConst.LuckyBagStatus.EXPIRED) {
                        ivLeftIcon.setImageResource(R.drawable.lucky_bag_message_gray)
                        ivLeftRight.setBackgroundResource(R.drawable.shape_lucky_bag_message_left_gray_bg)
                        ivLeftDiamond.setImageResource(R.drawable.ic_diamond1_gray)
                        ivLeftBomb.setImageResource(R.drawable.lucky_send_bag_bomb_coin_gray)
                        ivLeftNum.setImageResource(
                            BOMB_NUM_GRAY_RESOURCES.getOrNull(it.bombNum) ?: BOMB_NUM_GRAY_RESOURCES.first()
                        )
                        ivLeftHook.setImageResource(R.drawable.lucky_bag_received_hook_gray)

                        consLeftDetail.alpha = 1f
                    } else {
                        ivLeftIcon.setImageResource(R.drawable.lucky_bag_message_red)
                        ivLeftRight.setBackgroundResource(R.drawable.shape_lucky_bag_message_left_bg)
                        ivLeftDiamond.setImageResource(R.drawable.ic_diamond1)
                        ivLeftBomb.setImageResource(R.drawable.lucky_send_bag_bomb_coin)
                        ivLeftNum.setImageResource(
                            BOMB_NUM_RESOURCES.getOrNull(it.bombNum) ?: BOMB_NUM_RESOURCES.first()
                        )
                        ivLeftHook.setImageResource(R.drawable.lucky_bag_received_hook)

                        if (it.status == CommonConst.LuckyBagStatus.COMPLETED
                            || it.receiveStatus == AppConst.YES
                        ) {
                            consLeftDetail.alpha = 0.5f
                        } else {
                            consLeftDetail.alpha = 1f
                        }
                    }

                    if (it.receiveStatus == AppConst.YES) {
                        ivLeftHook.visibility = View.VISIBLE
                    } else {
                        ivLeftHook.visibility = View.GONE
                    }
                }
            }
        }

        private fun setTextRight(item: LuckyBagMessageResp) {
            mBinding.apply {
                clLeft.visibility = View.GONE
                clRight.visibility = View.VISIBLE

                layoutRightAvatar.avAvatar.setImageUrl(
                    UserManager.getUser().avatar,
                    UserManager.getUserId()
                )
                layoutRightAvatar.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(UserManager.getUser().decoration?.avatarFrame))

                tvRightTime.text =
                    SessionUtils.periodMessageTime(item.createTime)?.convertArabicDigitsToNormal()

                item.getBagMessage()?.also {
                    tvRightCoin.text = it.coins.toString()

                    if (it.status == CommonConst.LuckyBagStatus.EXPIRED) {
                        ivRightIcon.setImageResource(R.drawable.lucky_bag_message_gray)
                        ivRightLeft.setBackgroundResource(R.drawable.shape_lucky_bag_message_right_gray_bg)
                        ivRightDiamond.setImageResource(R.drawable.ic_diamond1_gray)
                        ivRightBomb.setImageResource(R.drawable.lucky_send_bag_bomb_coin_gray)
                        ivRightNum.setImageResource(
                            BOMB_NUM_GRAY_RESOURCES.getOrNull(it.bombNum) ?: BOMB_NUM_GRAY_RESOURCES.first()
                        )

                        consRightDetail.alpha = 1f
                    } else {
                        ivRightIcon.setImageResource(R.drawable.lucky_bag_message_red)
                        ivRightLeft.setBackgroundResource(R.drawable.shape_lucky_bag_message_right_bg)
                        ivRightDiamond.setImageResource(R.drawable.ic_diamond1)
                        ivRightBomb.setImageResource(R.drawable.lucky_send_bag_bomb_coin)
                        ivRightNum.setImageResource(
                            BOMB_NUM_RESOURCES.getOrNull(it.bombNum) ?: BOMB_NUM_RESOURCES.first()
                        )

                        if (it.status == CommonConst.LuckyBagStatus.COMPLETED) {
                            consRightDetail.alpha = 0.5f
                        } else {
                            consRightDetail.alpha = 1f
                        }
                    }
                }
            }
        }
    }

    private class LuckyBagPromptItemHolder(binding: AdapterLuckyBagItemPromptBinding) :
        BaseBindingViewHolder<AdapterLuckyBagItemPromptBinding, LuckyBagMessageResp>(binding) {

        override fun bind(item: LuckyBagMessageResp) {
            mBinding.apply {
                item.getPromptMessage()?.also {
                    tvPrompt.text = if (it.ownerUserId == UserManager.getUser().userId) {
                        StringUtils.getString(string.lucky_bag_prompt_other, resolveNickname(it.receiveNickname))
                    } else {
                        StringUtils.getString(string.lucky_bag_prompt_user, resolveNickname(it.ownerNickname))
                    }

                    ivBomb.visibility = if (it.bombStatus == AppConst.YES) {
                        View.VISIBLE
                    } else {
                        View.GONE
                    }
                }
            }
        }

        private fun resolveNickname(nickname: String): String {
            return if (nickname.length > 10) {
                nickname.substring(0, 10) + "..."
            } else {
                nickname
            }
        }
    }

    private class LuckyBagChatItemHolder(binding: AdapterLuckyBagChatItemBinding) :
        BaseBindingViewHolder<AdapterLuckyBagChatItemBinding, LuckyBagMessageResp>(binding) {
        override fun bind(item: LuckyBagMessageResp) {
            item.getChatMessage()?.let {
                mBinding.layoutRight.visibility = View.GONE
                mBinding.layoutLeft.visibility = View.GONE
                mBinding.bubbleLeft.bingTranslation(
                    mBinding.ivMessageTranslate,
                    mBinding.messageTextLeftTranslateLine,
                    mBinding.messageTextLeftTranslateLineRight
                )

                if (it.userBasic.userId == UserManager.getUserId()) {
                    setMySelfChatItem(mBinding, item, it)
                } else {
                    setOtherChatItem(mBinding, item, it)
                }
            }
        }

        private fun setMySelfChatItem(
            mBinding: AdapterLuckyBagChatItemBinding,
            item: LuckyBagMessageResp,
            luckyBagMessageChat: LuckyBagMessageResp.LuckyBagMessageChat,
        ) {
            mBinding.apply {
                layoutRight.visibility = View.VISIBLE
                bubbleRight.setBubble(DecorationUtils.getDecorationChatBubble(luckyBagMessageChat.userBasic.chatBubble))
                rightContentText.text = luckyBagMessageChat.content
                setHead(mBinding.layoutRightAvatar, luckyBagMessageChat)
            }
        }

        private fun setOtherChatItem(
            mBinding: AdapterLuckyBagChatItemBinding,
            item: LuckyBagMessageResp,
            luckyBagMessageChat: LuckyBagMessageResp.LuckyBagMessageChat,
        ) {
            mBinding.apply {
                layoutLeft.visibility = View.VISIBLE
                bubbleLeft.setBubble(DecorationUtils.getDecorationChatBubble(luckyBagMessageChat.userBasic.chatBubble))
                messageTextLeftText.text = luckyBagMessageChat.content
                setHead(layoutLeftAvatar, luckyBagMessageChat)
                //如果翻译文本的是空的  或者 翻译文本与原文本一样就隐藏
                if (luckyBagMessageChat.translationContent?.isEmpty() == true || luckyBagMessageChat.content == luckyBagMessageChat.translationContent) {
                    groupMessageTranslate.visibility = View.GONE
                } else {
                    groupMessageTranslate.visibility = View.VISIBLE
                    messageTextLeftTextTranslate.text = luckyBagMessageChat.translationContent
                }
            }
        }

        private fun setHead(
            layoutAvatar: LayoutMessageAdapterHeadBinding,
            luckyBagMessageChat: LuckyBagMessageResp.LuckyBagMessageChat,
        ) {
            layoutAvatar.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(luckyBagMessageChat.userBasic.avatarFrame))
            layoutAvatar.avAvatar.setImageUrl(
                luckyBagMessageChat.userBasic.avatar,
                luckyBagMessageChat.userBasic.userId
            )
        }
    }

    companion object {

        private const val ITEM_BAG = 0
        private const val ITEM_PROMPT = 1
        private const val ITEM_CHAT = 2

        private fun convertItemType(item: LuckyBagMessageResp): Int {
            return when (item.messageType) {
                CommonConst.LuckyBagMessageType.LUCKY_BAG -> ITEM_BAG
                CommonConst.LuckyBagMessageType.RECEIVE -> ITEM_PROMPT
                else -> ITEM_CHAT
            }
        }

        private val BOMB_NUM_RESOURCES = listOf(
            R.drawable.lucky_bomb_num_0,
            R.drawable.lucky_bomb_num_1,
            R.drawable.lucky_bomb_num_2,
            R.drawable.lucky_bomb_num_3,
            R.drawable.lucky_bomb_num_4,
            R.drawable.lucky_bomb_num_5,
            R.drawable.lucky_bomb_num_6,
            R.drawable.lucky_bomb_num_7,
            R.drawable.lucky_bomb_num_8,
            R.drawable.lucky_bomb_num_9
        )
        private val BOMB_NUM_GRAY_RESOURCES = listOf(
            R.drawable.lucky_bomb_num_0_gray,
            R.drawable.lucky_bomb_num_1_gray,
            R.drawable.lucky_bomb_num_2_gray,
            R.drawable.lucky_bomb_num_3_gray,
            R.drawable.lucky_bomb_num_4_gray,
            R.drawable.lucky_bomb_num_5_gray,
            R.drawable.lucky_bomb_num_6_gray,
            R.drawable.lucky_bomb_num_7_gray,
            R.drawable.lucky_bomb_num_8_gray,
            R.drawable.lucky_bomb_num_9_gray
        )
    }
}